# -*- coding: UTF-8 -*-
"""
任务的缓存解析后面也应该放到celery中，使用链式调用直接开始调度
"""
import asyncio

from celery import Task

from celery_app import celery_instance

async def ppp():
    print('-----pppp-----')
    a = 1/0
    return a


async def yprint():
    p = await ppp()
    print('-----yprint------')
    return p+100


class BaseDispatchTask(Task):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print('---------self.__init__--------')
        self.aaa = 3333
        print(self.max_retries)
        self.max_retries = 6

    def on_success(self, retval, task_id, args, kwargs):
        print(task_id)
        print('-----on_success------')
        pass

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        print('-----on_failure------')
        pass

    # def on_retry(self, exc, task_id, args, kwargs, einfo):  # fixme 重试任务需要与重试规则匹配
    #     # retry_await_second = data_block.get("retry_time_interval")  # fixme 延时时间
    #     # self.retry(exc=exc, cutdown=retry_await_second)
    #     print('----retry-------')
    #     print(args)
    #     pass

    def before_start(self, task_id, args, kwargs):
        print('-----------before_start-------')
        pass

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        print('--------after_return------')
        pass

@celery_instance.task(base=BaseDispatchTask, bind=True, max_retries=3)
def bean_dispatch_task(self):
    print(self.aaa)
    print(self.max_retries)
    try:
        1/0
    except Exception as e:
        # self.on_retry(args=(1,2,3,), task_id=self.task_id, exc=e, kwargs={"count_down": 1})
        self.retry(exc=TypeError('改变重试次数'), countdown=2, max_retries=1, custome="这是自定义的参数")
    # return asyncio.run(yprint())
    return 'aaaaaaaaaaaaaaaaaaaa'


@celery_instance.task(bind=True, name="parse.bean_parse_tasks.base_bean_parse",
                      max_retries=3, retry_backoff=1,
                      autoretry_for=[ZeroDivisionError])
def base_bean_parse(self, countdown):
    # todo
    print("success----")
    import asyncio
    try:
        a =  asyncio.run(yprint())
        b =  asyncio.run(yprint())

    except ZeroDivisionError as exc:
        print('-----retry--------')
        print(id(self))
        if countdown == 1:
            self.retry(exc=TypeError('改变重试次数'), countdown=countdown, args=(countdown,), max_retries=1, custome="这是自定义的参数")
        else:
            self.retry(exc=TypeError('自定义错误信息'), countdown=countdown, args=(countdown+1, ))
        # self.retry(args=None, kwargs=None, exc=exc, throw=True,
        #            eta=None, countdown=None, max_retries=None, **options)

